import { defineEventHandler } from 'h3'
import { randomBytes } from 'crypto'
import { writeFile } from 'fs/promises'
import { join } from 'path'
import {prisma} from '../utils/prisma'

export default defineEventHandler(async (event) => {
  const body = await readMultipartFormData(event)
  const file = body?.find(f => f.name === 'file')

  if (!file) {
    throw createError({ statusCode: 400, message: '未上传文件' })
  }

  // 生成6位取件码
  const code = randomBytes(3).toString('hex').toUpperCase()
  const fileName = file.filename || '未命名文件'
  const fileExt = fileName.split('.').pop() || ''
  const savedFileName = `${code}${fileExt ? '.' + fileExt : ''}`
  const filePath = join(process.cwd(), 'uploads', savedFileName)
  const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000) // 24小时后过期

  await writeFile(filePath, file.data)

  await prisma.file.create({
    data: {
      fileName,
      code,
      expiresAt,
      filePath
    }
  })

  return { code }
})